#!/usr/bin/env python3

################################################################################
# SPDX-FileCopyrightText: Copyright (c) 2019-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
################################################################################
import os
import random
import sys
import yaml
import cv2
import numpy as np
import datetime

# sys.path.append('../')

current_dir = os.path.dirname(os.path.abspath(__file__))
# 将上一级目录添加到 sys.path 中
# sys.path.append(os.path.join(current_dir, '..'))
sys.path.append(current_dir)
from utils.result_process import get_info, draw_bounding_boxes, is_flawed, test_is_flawed
from utils import logger

from pathlib import Path
import gi
import configparser
import argparse

gi.require_version('Gst', '1.0')
from gi.repository import GLib, Gst
from ctypes import *
import time
import sys
import math
import platform
from common.is_aarch_64 import is_aarch64
from common.bus_call import bus_call
from common.FPS import PERF_DATA

import pyds

no_display = True
silent = True
file_loop = False
perf_data = None
save_img = False
no_alert = True
test = False
test_interval = 1
image_ceiling = 200

MAX_DISPLAY_LEN = 64
PGIE_CLASS_ID_S = 0
PGIE_CLASS_ID_D = 1
PGIE_CLASS_ID_SS = 2
PGIE_CLASS_ID_DS = 3
PGIE_CLASS_ID_Stain = 4
PGIE_CLASS_ID_Discard = 5

MUXER_OUTPUT_WIDTH = 1920
MUXER_OUTPUT_HEIGHT = 1080
MUXER_BATCH_TIMEOUT_USEC = 4000000
TILED_OUTPUT_WIDTH = 960
TILED_OUTPUT_HEIGHT = 540
GST_CAPS_FEATURES_NVMM = "memory:NVMM"
OSD_PROCESS_MODE = 0
OSD_DISPLAY_TEXT = 1

MIN_CONFIDENCE = 0.5
MAX_CONFIDENCE = 1


# pgie_src_pad_buffer_probe  will extract metadata received on tiler sink pad
# and update params for drawing rectangle, object information etc.

def tiler_sink_pad_buffer_probe(pad, info, u_data):
    frame_number = 0
    num_rects = 0
    gst_buffer = info.get_buffer()
    if not gst_buffer:
        print("Unable to get GstBuffer ")
        return

    # Retrieve batch metadata from the gst_buffer
    # Note that pyds.gst_buffer_get_nvds_batch_meta() expects the
    # C address of gst_buffer as input, which is obtained with hash(gst_buffer)
    batch_meta = pyds.gst_buffer_get_nvds_batch_meta(hash(gst_buffer))

    l_frame = batch_meta.frame_meta_list
    while l_frame is not None:
        try:
            # Note that l_frame.data needs a cast to pyds.NvDsFrameMeta
            # The casting is done by pyds.NvDsFrameMeta.cast()
            # The casting also keeps ownership of the underlying memory
            # in the C code, so the Python garbage collector will leave
            # it alone.
            frame_meta = pyds.NvDsFrameMeta.cast(l_frame.data)


        except StopIteration:
            break

        l_obj = frame_meta.obj_meta_list
        frame_number = frame_meta.frame_num
        num_rects = frame_meta.num_obj_meta
        save_image = False
        # logger.logger.info(f"{frame_meta.pad_index}的第{frame_number}帧")
        obj_counter = {
            PGIE_CLASS_ID_S: 0,
            PGIE_CLASS_ID_D: 0,
            PGIE_CLASS_ID_SS: 0,
            PGIE_CLASS_ID_DS: 0,
            PGIE_CLASS_ID_Stain: 0,
            PGIE_CLASS_ID_Discard: 0
        }

        obj_list = []
        frame_copy = None

        while l_obj is not None:
            try:
                # Casting l_obj.data to pyds.NvDsObjectMeta
                obj_meta = pyds.NvDsObjectMeta.cast(l_obj.data)
            except StopIteration:
                break
            obj_counter[obj_meta.class_id] += 1
            # Periodically check for objects with borderline confidence value that may be false positive detections.
            # If such detections are found, annotate the frame with bboxes and confidence value.
            # Save the annotated frame to file.

            if MIN_CONFIDENCE < obj_meta.confidence < MAX_CONFIDENCE:
                # Getting Image data using nvbufsurface
                # the input should be address of buffer and batch_id
                n_frame = pyds.get_nvds_buf_surface(hash(gst_buffer), frame_meta.batch_id)

                obj_info = get_info(n_frame=n_frame, obj_meta=obj_meta, confidence=obj_meta.confidence)
                obj_list.append(obj_info)

                n_frame = draw_bounding_boxes(n_frame, obj_meta, obj_meta.confidence)
                # convert python array into numpy array format in the copy mode.
                frame_copy = np.array(n_frame, copy=True, order='C')
                # convert the array into cv2 default color format
                frame_copy = cv2.cvtColor(frame_copy, cv2.COLOR_RGBA2BGRA)

                save_image = True

            try:
                l_obj = l_obj.next
            except StopIteration:
                break

        stream_index = "stream{0}".format(frame_meta.pad_index)
        global perf_data
        perf_data.update_fps(stream_index)
        if not silent:
            print("Frame Number=", frame_number, "Number of Objects=", num_rects, "[",
                  obj_counter[PGIE_CLASS_ID_S], obj_counter[PGIE_CLASS_ID_D], obj_counter[PGIE_CLASS_ID_SS],
                  obj_counter[PGIE_CLASS_ID_DS], obj_counter[PGIE_CLASS_ID_Stain], obj_counter[PGIE_CLASS_ID_Discard],
                  "]")

        if save_image:
            # img_path = "{}/stream_{}/frame_{}.jpg".format("frames", frame_meta.pad_index, frame_number)
            # cv2.imwrite(img_path, frame_copy)
            global save_img, no_alert
            if save_img and len(os.listdir("../samples/images/source{}".format(frame_meta.pad_index + 1))) < image_ceiling:
                logger.logger.info("保存这一帧")
                img_path = "../samples/images/source{}/frame_{}.jpg".format(frame_meta.pad_index + 1 ,
                                                                                        frame_number)
                cv2.imwrite(os.path.join(current_dir, img_path), frame_copy)
            if not no_alert:
                is_flawed(obj_list, frame_meta.pad_index, frame_copy)

        try:
            l_frame = l_frame.next
        except StopIteration:
            break

    return Gst.PadProbeReturn.OK



def test_probe(pad, info, u_data):
    last_time = time.time() + random.uniform(1,5)
    gst_buffer = info.get_buffer()
    if not gst_buffer:
        print("Unable to get GstBuffer ")
        return

    # Retrieve batch metadata from the gst_buffer
    # Note that pyds.gst_buffer_get_nvds_batch_meta() expects the
    # C address of gst_buffer as input, which is obtained with hash(gst_buffer)
    batch_meta = pyds.gst_buffer_get_nvds_batch_meta(hash(gst_buffer))

    l_frame = batch_meta.frame_meta_list
    while l_frame is not None:
        try:
            # Note that l_frame.data needs a cast to pyds.NvDsFrameMeta
            # The casting is done by pyds.NvDsFrameMeta.cast()
            # The casting also keeps ownership of the underlying memory
            # in the C code, so the Python garbage collector will leave
            # it alone.
            frame_meta = pyds.NvDsFrameMeta.cast(l_frame.data)


        except StopIteration:
            break

        l_obj = frame_meta.obj_meta_list
        frame_number = frame_meta.frame_num
        num_rects = frame_meta.num_obj_meta
        #logger.logger.info(f"{frame_meta.pad_index}的第{frame_number}帧")
        obj_counter = {
            PGIE_CLASS_ID_S: 0,
            PGIE_CLASS_ID_D: 0,
            PGIE_CLASS_ID_SS: 0,
            PGIE_CLASS_ID_DS: 0,
            PGIE_CLASS_ID_Stain: 0,
            PGIE_CLASS_ID_Discard: 0
        }

        obj_list = []
        frame_copy = None

        # 添加定时保存图片功能
        n_frame = pyds.get_nvds_buf_surface(hash(gst_buffer), frame_meta.batch_id)
        # convert python array into numpy array format in the copy mode.
        frame_copy = np.array(n_frame, copy=True, order='C')
        # convert the array into cv2 default color format
        frame_copy = cv2.cvtColor(frame_copy, cv2.COLOR_RGBA2BGRA)


        stream_index = "stream{0}".format(frame_meta.pad_index)
        global perf_data
        perf_data.update_fps(stream_index)
        frame_copy = np.random.randint(0,256,(1920,1080,4), dtype=np.uint8)
        current_time = time.time()
        if save_img and (current_time - last_time) > test_interval:
            if len(os.listdir("../samples/images/source{}".format(frame_meta.pad_index + 1))) < image_ceiling:

                img_path = "../samples/images/source{}/frame_{}.jpg".format(frame_meta.pad_index + 1,
                                                                        frame_number)
                cv2.imwrite(os.path.join(current_dir, img_path), frame_copy)

        test_is_flawed(frame_meta.pad_index, frame_copy)
        try:
            l_frame = l_frame.next
        except StopIteration:
            break

    return Gst.PadProbeReturn.OK

def cb_newpad(decodebin, decoder_src_pad, data):
    print("In cb_newpad\n")
    caps = decoder_src_pad.get_current_caps()
    if not caps:
        caps = decoder_src_pad.query_caps()
    gststruct = caps.get_structure(0)
    gstname = gststruct.get_name()
    source_bin = data
    features = caps.get_features(0)

    # Need to check if the pad created by the decodebin is for video and not
    # audio.
    print("gstname=", gstname)
    if (gstname.find("video") != -1):
        # Link the decodebin pad only if decodebin has picked nvidia
        # decoder plugin nvdec_*. We do this by checking if the pad caps contain
        # NVMM memory features.
        print("features=", features)
        if features.contains("memory:NVMM"):
            # Get the source bin ghost pad
            bin_ghost_pad = source_bin.get_static_pad("src")
            if not bin_ghost_pad.set_target(decoder_src_pad):
                sys.stderr.write("Failed to link decoder src pad to source bin ghost pad\n")
        else:
            sys.stderr.write(" Error: Decodebin did not pick nvidia decoder plugin.\n")


def decodebin_child_added(child_proxy, Object, name, user_data):
    print("Decodebin child added:", name, "\n")
    if (name.find("decodebin") != -1):
        Object.connect("child-added", decodebin_child_added, user_data)

    if "source" in name:
        source_element = child_proxy.get_by_name("source")
        if source_element.find_property('drop-on-latency') != None:
            Object.set_property("drop-on-latency", True)


def create_source_bin(index, uri):
    print("Creating source bin")

    # Create a source GstBin to abstract this bin's content from the rest of the
    # pipeline
    bin_name = "source-bin-%02d" % index
    print(bin_name)
    nbin = Gst.Bin.new(bin_name)
    if not nbin:
        sys.stderr.write(" Unable to create source bin \n")

    # Source element for reading from the uri.
    # We will use decodebin and let it figure out the container format of the
    # stream and the codec and plug the appropriate demux and decode plugins.
    if file_loop:
        # use nvurisrcbin to enable file-loop
        uri_decode_bin = Gst.ElementFactory.make("nvurisrcbin", "uri-decode-bin")
        uri_decode_bin.set_property("file-loop", 1)
    else:
        uri_decode_bin = Gst.ElementFactory.make("uridecodebin", "uri-decode-bin")
    if not uri_decode_bin:
        sys.stderr.write(" Unable to create uri decode bin \n")
    # We set the input uri to the source element
    uri_decode_bin.set_property("uri", uri)
    # Connect to the "pad-added" signal of the decodebin which generates a
    # callback once a new pad for raw data has beed created by the decodebin
    uri_decode_bin.connect("pad-added", cb_newpad, nbin)
    uri_decode_bin.connect("child-added", decodebin_child_added, nbin)

    # We need to create a ghost pad for the source bin which will act as a proxy
    # for the video decoder src pad. The ghost pad will not have a target right
    # now. Once the decode bin creates the video decoder and generates the
    # cb_newpad callback, we will set the ghost pad target to the video decoder
    # src pad.
    Gst.Bin.add(nbin, uri_decode_bin)
    bin_pad = nbin.add_pad(Gst.GhostPad.new_no_target("src", Gst.PadDirection.SRC))
    if not bin_pad:
        sys.stderr.write(" Failed to add ghost pad in source bin \n")
        return None
    return nbin


def main(args, requested_pgie=None, config=None, disable_probe=False):
    global perf_data
    perf_data = PERF_DATA(len(args))

    number_sources = len(args)

    # Standard GStreamer initialization
    Gst.init(None)

    # Create gstreamer elements */
    # Create Pipeline element that will form a connection of other elements
    print("Creating Pipeline \n ")
    pipeline = Gst.Pipeline()
    is_live = False

    if not pipeline:
        sys.stderr.write(" Unable to create Pipeline \n")
    print("Creating streamux \n ")
    # 1. 创建element
    # Create nvstreammux instance to form batches from one or more sources.
    streammux = Gst.ElementFactory.make("nvstreammux", "Stream-muxer")
    if not streammux:
        sys.stderr.write(" Unable to create NvStreamMux \n")

    pipeline.add(streammux)
    for i in range(number_sources):
        print("Creating source_bin ", i, " \n ")
        uri_name = args[i]
        if uri_name.find("rtsp://") == 0:
            is_live = True
        source_bin = create_source_bin(i, uri_name)
        if not source_bin:
            sys.stderr.write("Unable to create source bin \n")
        pipeline.add(source_bin)
        padname = "sink_%u" % i
        sinkpad = streammux.get_request_pad(padname)
        if not sinkpad:
            sys.stderr.write("Unable to create sink pad bin \n")
        srcpad = source_bin.get_static_pad("src")
        if not srcpad:
            sys.stderr.write("Unable to create src pad bin \n")
        srcpad.link(sinkpad)
    # 2. 创建queue并添加到pipeline
    queue1 = Gst.ElementFactory.make("queue", "queue1")
    queue2 = Gst.ElementFactory.make("queue", "queue2")
    queue3 = Gst.ElementFactory.make("queue", "queue3")
    queue4 = Gst.ElementFactory.make("queue", "queue4")
    queue5 = Gst.ElementFactory.make("queue", "queue5")
    queue6 = Gst.ElementFactory.make("queue", "queue6")
    queue7 = Gst.ElementFactory.make("queue", "queue7")

    pipeline.add(queue1)
    pipeline.add(queue2)
    pipeline.add(queue3)
    pipeline.add(queue4)
    pipeline.add(queue5)
    pipeline.add(queue6)
    pipeline.add(queue7)

    nvdslogger = None
    transform = None

    print("Creating Pgie \n ")
    if requested_pgie != None and (requested_pgie == 'nvinferserver' or requested_pgie == 'nvinferserver-grpc'):
        pgie = Gst.ElementFactory.make("nvinferserver", "primary-inference")
    elif requested_pgie != None and requested_pgie == 'nvinfer':
        pgie = Gst.ElementFactory.make("nvinfer", "primary-inference")
    else:
        pgie = Gst.ElementFactory.make("nvinfer", "primary-inference")

    if not pgie:
        sys.stderr.write(" Unable to create pgie :  %s\n" % requested_pgie)

    if disable_probe:
        # Use nvdslogger for perf measurement instead of probe function
        print("Creating nvdslogger \n")
        nvdslogger = Gst.ElementFactory.make("nvdslogger", "nvdslogger")

    # 3. 添加一些组件，以便保存图片
    print("Creating nvvidconv1 \n ")
    nvvidconv1 = Gst.ElementFactory.make("nvvideoconvert", "convertor1")
    if not nvvidconv1:
        sys.stderr.write(" Unable to create nvvidconv1 \n")
    print("Creating filter1 \n ")
    caps1 = Gst.Caps.from_string("video/x-raw(memory:NVMM), format=RGBA")
    filter1 = Gst.ElementFactory.make("capsfilter", "filter1")
    if not filter1:
        sys.stderr.write(" Unable to get the caps filter1 \n")
    filter1.set_property("caps", caps1)

    print("Creating tiler \n ")
    tiler = Gst.ElementFactory.make("nvmultistreamtiler", "nvtiler")
    if not tiler:
        sys.stderr.write(" Unable to create tiler \n")
    print("Creating nvvidconv \n ")
    nvvidconv = Gst.ElementFactory.make("nvvideoconvert", "convertor")
    if not nvvidconv:
        sys.stderr.write(" Unable to create nvvidconv \n")
    print("Creating nvosd \n ")
    nvosd = Gst.ElementFactory.make("nvdsosd", "onscreendisplay")
    if not nvosd:
        sys.stderr.write(" Unable to create nvosd \n")
    nvosd.set_property('process-mode', OSD_PROCESS_MODE)
    nvosd.set_property('display-text', OSD_DISPLAY_TEXT)

    if no_display:
        print("Creating Fakesink \n")
        sink = Gst.ElementFactory.make("fakesink", "fakesink")
        sink.set_property('enable-last-sample', 0)
        sink.set_property('sync', 0)
    else:
        if (is_aarch64()):
            print("Creating transform \n ")
            transform = Gst.ElementFactory.make("nvegltransform", "nvegl-transform")
            if not transform:
                sys.stderr.write(" Unable to create transform \n")
        print("Creating EGLSink \n")
        sink = Gst.ElementFactory.make("nveglglessink", "nvvideo-renderer")

    if not sink:
        sys.stderr.write(" Unable to create sink element \n")

    if is_live:
        print("At least one of the sources is live")
        streammux.set_property('live-source', 1)

    streammux.set_property('width', 1920)
    streammux.set_property('height', 1080)
    streammux.set_property('batch-size', number_sources)
    streammux.set_property('batched-push-timeout', 4000000)
    if requested_pgie == "nvinferserver" and config != None:
        pgie.set_property('config-file-path', config)
    elif requested_pgie == "nvinferserver-grpc" and config != None:
        pgie.set_property('config-file-path', config)
    elif requested_pgie == "nvinfer" and config != None:
        pgie.set_property('config-file-path', config)
    else:
        current_script_dir = os.path.dirname(os.path.abspath(__file__))

        pgie.set_property('config-file-path', os.path.join(current_script_dir, "../conf/yolo_config.txt"))
    pgie_batch_size = pgie.get_property("batch-size")
    if (pgie_batch_size != number_sources):
        print("WARNING: Overriding infer-config batch-size", pgie_batch_size, " with number of sources ",
              number_sources, " \n")
        pgie.set_property("batch-size", number_sources)
    tiler_rows = int(math.sqrt(number_sources))
    tiler_columns = int(math.ceil((1.0 * number_sources) / tiler_rows))
    tiler.set_property("rows", tiler_rows)
    tiler.set_property("columns", tiler_columns)
    tiler.set_property("width", TILED_OUTPUT_WIDTH)
    tiler.set_property("height", TILED_OUTPUT_HEIGHT)
    sink.set_property("qos", 0)
    # 4. 添加 pgie tiler nvvidconv nvosd tansform sink到pipeline
    print("Adding elements to Pipeline \n")
    pipeline.add(pgie)
    if nvdslogger:
        pipeline.add(nvdslogger)
    pipeline.add(tiler)
    pipeline.add(nvvidconv)
    pipeline.add(nvosd)

    pipeline.add(filter1)
    pipeline.add(nvvidconv1)

    if transform:
        pipeline.add(transform)
    pipeline.add(sink)
    # 5. 连接elements 顺序：streammux-queue1-pgie-quque2-nvvidconv1-queue6
    # -filter1-queue7-tiler-queue3-nvvidconv-queue4-nvosd-queue5-transform-sink
    print("Linking elements in the Pipeline \n")
    streammux.link(queue1)
    queue1.link(pgie)
    pgie.link(queue2)
    if nvdslogger:
        queue2.link(nvdslogger)
        # nvdslogger.link(tiler)
        nvdslogger.link(nvvidconv1)
        nvvidconv1.link(queue6)
        queue6.link(filter1)
        filter1.link(queue7)
        queue7.link(tiler)
    else:
        # queue2.link(tiler)
        queue2.link(nvvidconv1)
        nvvidconv1.link(queue6)
        queue6.link(filter1)
        filter1.link(queue7)
        queue7.link(tiler)

    tiler.link(queue3)
    queue3.link(nvvidconv)
    nvvidconv.link(queue4)
    queue4.link(nvosd)
    if transform:
        nvosd.link(queue5)
        queue5.link(transform)
        transform.link(sink)
    else:
        nvosd.link(queue5)
        queue5.link(sink)

    # create an event loop and feed gstreamer bus mesages to it

    # 6. 创建loop
    loop = GLib.MainLoop()
    bus = pipeline.get_bus()
    bus.add_signal_watch()
    bus.connect("message", bus_call, loop)
    # pgie_src_pad = pgie.get_static_pad("src")
    # if not pgie_src_pad:
    #     sys.stderr.write(" Unable to get src pad \n")
    # else:
    #     if not disable_probe:
    #         pgie_src_pad.add_probe(Gst.PadProbeType.BUFFER, pgie_src_pad_buffer_probe, 0)
    #         # perf callback function to print fps every 5 sec
    #         GLib.timeout_add(5000, perf_data.perf_print_callback)

    # 7. 给tiler创建pad，用add_probe把probe方法加入tiler中
    tiler_sink_pad = tiler.get_static_pad("sink")
    if not tiler_sink_pad:
        sys.stderr.write(" Unable to get src pad \n")
    else:
        if test:
            tiler_sink_pad.add_probe(Gst.PadProbeType.BUFFER, test_probe, 0)
        else:
            tiler_sink_pad.add_probe(Gst.PadProbeType.BUFFER, tiler_sink_pad_buffer_probe, 0)
        # perf callback function to print fps every 5 sec
        GLib.timeout_add(5000, perf_data.perf_print_callback)

    # List the sources
    print("Now playing...")
    for i, source in enumerate(args):
        print(i, ": ", source)

    print("Starting pipeline \n")
    # start play back and listed to events
    pipeline.set_state(Gst.State.PLAYING)
    try:
        loop.run()
    except:
        pass

    # cleanup
    print("Exiting app\n")
    pipeline.set_state(Gst.State.NULL)



if __name__ == '__main__':
    # 获取当前脚本所在的目录
    # stream_paths, pgie, config, disable_probe = parse_args()
    current_dir = os.path.dirname(os.path.abspath(__file__))
    yaml_path = os.path.join(current_dir, "../conf/yolo.yaml")
    with open(yaml_path, 'r') as file:
        data = yaml.safe_load(file)
    save_img = data['save_img']
    no_alert = data['no_alert']
    no_display = data['no_display']
    silent = data['silent']
    test = data['test']
    test_interval = int(data['test_interval'])
    image_ceiling = int(data['image_ceiling'])
    # logger.logger.info(data)
    # 如果开启图片保存，要先创建文件夹
    if save_img:
        path1 = os.path.join(current_dir, "../samples/images/source1")
        path2 = os.path.join(current_dir, "../samples/images/source2")
        path3 = os.path.join(current_dir, "../samples/images/source3")
        if not os.path.exists(path1):
            os.makedirs(path1)
        if not os.path.exists(path2):
            os.makedirs(path2)
        if not os.path.exists(path3):
            os.makedirs(path3)

    sys.exit(main(data['streams']))

    # main(stream_paths, pgie, config, disable_probe)
